package com.adnaan.admin.controller.auth;

import cn.dev33.satoken.stp.StpUtil;
import com.adnaan.admin.service.SysUserService;
import com.adnaan.common.model.Result;
import com.adnaan.common.model.dto.auth.LoginRequest;
import com.adnaan.common.model.dto.auth.LoginResponse;
import com.adnaan.common.utils.PasswordUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 后台管理员认证控制器
 */
@Tag(name = "后台认证接口", description = "管理员登录认证")
@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminAuthController {

    private final SysUserService sysUserService;

    /**
     * 管理员登录
     */
    @Operation(summary = "管理员登录", description = "获取访问令牌")
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        // 调用登录方法
        LoginResponse loginResponse = adminLogin(loginRequest);
        return Result.success("登录成功", loginResponse);
    }

    /**
     * 管理员登出
     */
    @Operation(summary = "管理员登出", description = "退出登录")
    @PostMapping("/logout")
    public Result<String> logout() {
        StpUtil.logout();
        return Result.success("登出成功");
    }

    /**
     * 获取当前管理员信息
     */
    @Operation(summary = "获取当前管理员信息", description = "获取当前登录管理员信息")
    @GetMapping("/info")
    public Result<LoginResponse> getInfo() {
        // 获取当前管理员ID
        Long userId = StpUtil.getLoginIdAsLong();

        // 查询用户信息
        LoginResponse adminInfo = getCurrentAdminInfo(userId);
        return Result.success(adminInfo);
    }

    /**
     * 管理员登录逻辑
     */
    private LoginResponse adminLogin(LoginRequest loginRequest) {
        // 查询用户
        var user = sysUserService.getByUsername(loginRequest.getUsername());
        if (user == null) {
            throw new com.adnaan.common.exception.BusinessException("用户名或密码错误");
        }

        // 校验密码
        if (!PasswordUtil.matches(loginRequest.getPassword(), user.getPassword())) {
            throw new com.adnaan.common.exception.BusinessException("用户名或密码错误");
        }

        // 校验用户状态
        if (user.getStatus() != 0) {
            throw new com.adnaan.common.exception.BusinessException("账号已被禁用");
        }

        // 执行登录
        StpUtil.login(user.getId());
        String token = StpUtil.getTokenValue();

        // 获取角色和权限
        var roles = sysUserService.getRoleKeys(user.getId());
        var permissions = sysUserService.getPermissions(user.getId());

        // 返回登录信息
        return LoginResponse.builder()
                .userId(user.getId())
                .username(user.getUsername())
                .nickname(user.getNickname())
                .avatar(user.getAvatar())
                .token(token)
                .roles(roles)
                .permissions(permissions)
                .build();
    }

    /**
     * 获取当前管理员信息
     */
    private LoginResponse getCurrentAdminInfo(Long userId) {
        // 查询用户
        var user = sysUserService.getById(userId);
        if (user == null) {
            throw new com.adnaan.common.exception.BusinessException("用户不存在");
        }

        // 获取角色和权限
        var roles = sysUserService.getRoleKeys(userId);
        var permissions = sysUserService.getPermissions(userId);

        // 返回用户信息
        return LoginResponse.builder()
                .userId(user.getId())
                .username(user.getUsername())
                .nickname(user.getNickname())
                .avatar(user.getAvatar())
                .token(StpUtil.getTokenValue())
                .roles(roles)
                .permissions(permissions)
                .build();
    }
}